package com.xiaoy.core.base.security.org.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xiaoy.core.base.security.org.entity.Org;
import com.xiaoy.core.base.security.role.entity.Role;
import com.xiaoy.core.base.util.store.config.ConfigTable;
import com.xiaoy.dao.DaoUtil;
@Service
public class OrgService {

	@Resource(name="daoUtil")
	private DaoUtil dao ;
	
	/**
	 * 根据userId得到所属部门，暂时一个用户只能在一个部门下，所以list的size最大为1.后面一个用户可以同时在多个部门下
	 * @param userId
	 * @return
	 * @throws Exception
	 * TODO
	 */
	public List<Org> getByUser (long userId) throws Exception{
		
		String sql = "select * from " + ConfigTable.Security.ORG_TABLENAME
				+ " where id (select * from "
				+ ConfigTable.Security.ORG_USER_TABLENAME
				+ " ur where ur.user_id = ?)";
		return (List<Org>) dao.query(Org.class, sql, userId);
	}
	
	/**
	 * 通过机构id 获得所有的角色
	 * @param 组织机构id
	 * @return
	 * TODO
	 */
	public List<Role>getParentOrgMergeRole (long id) {
		
		String sql = "select * from " + ConfigTable.Security.ROLE_TABLENAME
				+ " where id in ("
				+ " select role_id from sys_org_role org_role " 
				+ "  where "
				+ "  effect = '1' and " 
				+ "  org_role.org_id in "
				+ "  (SELECT o.id " 
				+ "   FROM sys_org o "
				+ "   where o.merge = '1' " 
				+ "         START WITH id = ? "
				+ "         CONNECT BY PRIOR pid = id) )";
		return (List<Role>) dao.query(Role.class, sql, id);
	}
	
	/**
	 * 得到所有的上级机构
	 * @param org
	 * @return
	 * @throws Exception
	 * TODO
	 */
	public List<Org> getParents (Org org) throws Exception{
		
		List<Org> orgs = new ArrayList<Org>();
		getParentOrgRole(org,orgs);
		return orgs;
	}
	
	private Org getParentOrgRole(Org org,List<Org>orgs) {
		
		Org parent = org.getParent();
		if (parent!=null&&parent.getId()!=0) {
			if ("1".equals(parent.getMerge())) {
				orgs.add(parent);
			}
			return getParentOrgRole(org.getParent(),orgs);
		}
		return null;
	}
}
